<template>
  <div id="danmaku">
    <div id="danmakuBar" style='-webkit-app-region: drag;'>
      <i class="el-icon-rank"></i>
      <span id="sTitle">{{ sTitle }} {{ sOnlineCount }}</span>
      <i class="el-icon-close" style='-webkit-app-region: no-drag; color: #ff0000; float: right;' @click="close"></i>
    </div>

      <div id="danmakuList">
        {{ err }}
        <div class="danmakuTxt" v-for="(item, index) in listShow" v-bind:key="index">
          <img v-if="item.avatar" :src="'https://source.48.cn' + item.avatar" v-on:click="showPicMsgBox('https://source.48.cn' + item.avatar)" width="24px" height="24px" style="border-radius: 50%; vertical-align:middle;"/>
          <span id='user'>{{ item.user }}</span> <span id='time'>{{ item.time.replace("00:", "").replace("[", "").replace("]", "") }}</span> <span v-if="item.isSelf" style="background-color: #efef00;">自己</span> 
          <span id='text'>{{ item.text }}</span>
          <span id='phone'>{{ item.phone }}</span>
        </div>
      </div>

    <el-row id="danmakuPanel">
      <el-col :span="6">
        <el-button v-on:click="pause" size="mini" circle> <img v-if="!paused" src="https://www.easyicon.net/api/resizeApi.php?id=524978&size=16"/> <img v-if="paused" src="https://www.easyicon.net/api/resizeApi.php?id=524981&size=16"/></el-button><span v-if="notLive" style="font-size: 12px;"> {{ this.$myutil.getDanmakuTimeStr(currentTime) }} </span>
      </el-col>
      <el-col v-if="notLive" :span="18">
        <el-slider v-model="position" :max="max" @change="locat" :format-tooltip="formatTooltip"></el-slider>
      </el-col>
      <el-col v-if="!notLive" :span="14">
        <el-input id="textSend" width="100px" type="text" @focus="focusText($event)" v-model="sText" placeholder="请输入要发送的弹幕内容" size="mini" disabled/>
      </el-col>
      <el-col v-if="!notLive" :span="4">
        <el-button v-on:click="sendDanmaku(sText)" size="mini" circle disabled>发送</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import '../../api/NIM_Web_SDK_v5.4.0.js'
import '../../api/NIM_Web_NIM_v5.4.0.js'
import '../../api/NIM_Web_Chatroom_v5.4.0.js'
import { remote } from 'electron'

export default {
  name: 'danmaku-page',
  data () {
    return {
      listLrc: [],
      listShow: [],
      currentTime: 0, // 当前播放经过时间
      currentIndex: 0, // 当前播放listLrc索引
      InterShow: 0, // 播放弹幕计时器id
      position: 0,
      max: 0,
      flagLocat: false,
      paused: true,
      err: '',
      chat: null,
      notLive: true,
      sText: '',
      liveId: '',
      chatroomId: 0,
      liveStartTime: 0,
      sTitle: '',
      sOnlineCount: '',
      getMembers: null,
      mapUserCount: new Map() // 记录一下有多个人发过弹幕
    }
  },
  methods: {
    close () {
      window.close()
    },
    pause () {
      this.paused = !this.paused
    },
    locat () {
      this.flagLocat = true
    },
    focusText (event) {
      event.currentTarget.select()
    },
    formatTooltip (val) {
      return this.$myutil.getDanmakuTimeStr(val)
    },
    showPicMsgBox (urlPic) {
      const h = this.$createElement
      this.$msgbox({
        title: '图片查看',
        message: h('p', null, [
          h('img', { attrs: {src: urlPic}, style: 'maxHeight: 540px; maxWidth: 360px;' }, null),
          h('span', { style: 'size: 10px; word-break:normal; width:auto; display:block; white-space: pre-wrap; word-wrap: break-word; overflow: hidden;' }, urlPic)
        ]),
        confirmButtonText: '下载图片',
        showCancelButton: true,
        cancelButtonText: '关闭',
        center: true
      }).then(action => {
        this.downloadPic(urlPic)
      }).catch(() => {

      })
    },
    downloadPic (urlPic) {
      var request = require('request')
      var fs = require('fs')
      if (urlPic) {
        const file = remote.dialog.showSaveDialog(remote.getCurrentWindow(), {
          filters: [
            {name: 'Image Files', extensions: ['jpg', 'jpeg', 'png', 'bmp']},
            {name: 'All Files', extensions: ['*']}]
        })
        if (file) {
          request(urlPic).pipe(fs.createWriteStream(file))
          this.$message({
            type: 'success',
            message: '图片已保存至' + file
          })
        }
      }
    },
    clearListShow () {
      var v = this
      // 清除聊天室播放
      if (v.chat) {
        v.chat.disconnect()
      }
      // 清除下载弹幕文件播放
      if (v.InterShow > 0) {
        clearInterval(v.InterShow)
        v.InterShow = 0
      }
      v.currentTime = 0
      v.currentIndex = 0
      v.position = 0
      v.paused = true
      v.notLive = true
      v.err = null
      v.listLrc = []
      v.listShow = []
    },
    getChatroom (chatroomId, liveId, startTime) {
      var v = this
      v.clearListShow()
      v.notLive = false
      v.liveId = liveId
      v.chatroomId = chatroomId
      v.liveStartTime = startTime
      let lastEnterTime = 0
      let membersCount = 0
      /* eslint-disable */
      v.chat = new Chatroom({
        appKey: '632feff1f4c838541ab75195d1ceb3fa',
        account: '481026', // 48webbKixCnX7
        token: '481026',
        chatroomId: chatroomId,
        chatroomAddresses: [
          'weblink03.netease.im:443'
        ],
        onconnect: onChatroomConnect,
        onerror: onChatroomError,
        onwillreconnect: onChatroomWillReconnect,
        ondisconnect: onChatroomDisconnect,
        // 消息
        onmsgs: onChatroomMsgs
      })
      /* eslint-enable */
      console.log(v.chat)
      function onChatroomConnect (chatroomInfo) {
        console.log('进入聊天室', chatroomInfo)
        v.paused = false
        v.err = '进入直播聊天室'
        v.getMembers = function () {
          v.chat.getChatroomMembers({
            guest: true,
            onlyOnline: true,
            time: lastEnterTime, // 取上一次最后一个游客的enterTime,来开始获取下一页
            limit: 200, // 分页最多200一次
            done: getChatroomMembersDone
          })
          function getChatroomMembersDone (error, obj) {
            console.log('获取聊天室成员' + (!error ? '成功' : '失败'), error, obj)
            membersCount += obj.members.length
            if (obj.members.length > 0) {
              lastEnterTime = obj.members[obj.members.length - 1].enterTime
            }
            if (obj.members.length >= 200) {
              v.getMembers() // 递归获取
            } else {
              v.sOnlineCount = '(人数:' + membersCount + ')'
              lastEnterTime = 0
              membersCount = 0
            }
          }
        }
        v.getMembers()
        setInterval(v.getMembers, 1000 * 60) // 一分钟获取一次聊天室人数
      }
      function onChatroomWillReconnect (obj) {
      // 此时说明 `SDK` 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
        console.log('即将重连', obj)
      }
      function onChatroomDisconnect (error) {
      // 此时说明 `SDK` 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
        console.log('连接断开', error)
        if (error) {
          switch (error.code) {
          // 账号或者密码错误, 请跳转到登录页面并提示错误
            case 302:
              break
              // 被踢, 请提示错误后跳转到登录页面
            case 'kicked':
              break
            default:
              break
          }
        }
      }
      function onChatroomError (error, obj) {
        console.log('发生错误', error, obj)
      }
      function onChatroomMsgs (msgs) {
        // console.log('收到聊天室消息', msgs)
        for (let i = 0; i < msgs.length; i++) {
          if (msgs[i].from !== 'admin') {
            let jsonCustom = JSON.parse(msgs[i].custom)
            // console.log(msgs[i].custom)
            if (jsonCustom.messageType === 'BARRAGE_NORMAL') { // 1为弹幕
              // console.log(v.liveStartTime)
              let sec = Math.floor((msgs[i].time - v.liveStartTime) / 1000)
              let item = {
                time: v.$myutil.getDanmakuTimeStr(sec),
                sec: sec,
                user: jsonCustom.user.nickName,
                text: jsonCustom.text,
                avatar: jsonCustom.user.avatar,
                phone: jsonCustom.config.phoneName
              }
              v.listShow.push(item)
              if (!v.paused) {
                v.$nextTick(function () {
                  var divList = document.getElementById('danmakuList')
                  divList.scrollTop = divList.scrollHeight
                })
              }
            } else {
              // console.log('礼物')
            }
          } else if (msgs[i].type === 'notification') {
            // console.log('通知')
          } else if (msgs[i].type === 'text') {
            // console.log('信息')
          }
        }
      }
    },
    sendDanmaku (sDanmaku) {
      var v = this
      if (!sDanmaku || sDanmaku === '') {
        v.$notify({
          title: '消息',
          message: '评论内容不能为空!',
          position: 'bottom-right',
          type: 'warning',
          duration: 2000
        })
      }
      var custom = {
        sourceId: this.liveId,
        sessionRole: 0,
        messageType: 'BARRAGE_NORMAL',
        fromApp: '201811',
        module: 'session',
        bubbleId: '0',
        inTop: false,
        text: sDanmaku,
        moudule: 'live',
        user: {
          gender: 0,
          sessionRole: 0,
          level: 2,
          nickName: '机器人7',
          roleId: 1,
          avatar: '/mediasource/avatar/61730.jpg',
          badgeCount: 0,
          userId: 10000,
          friends: 0,
          badge: [],
          followers: 0,
          isStar: false,
          money: 0,
          isOwener: false,
          exp: 0,
          vip: false,
          support: 0,
          card: 0,
          verification: false
        },
        config: {
          build: '190415',
          phoneName: 'Mi 9',
          version: '6.0.0',
          mobileOperators: '中国移动',
          ip: '192.168.1.123',
          phoneSystemVersion: '9.0'
        },
        roomId: this.chatroomId
      }
      var msg = this.chat.sendText({
        text: sDanmaku,
        type: 'text',
        custom: JSON.stringify(custom),
        chatroomId: this.chatroomId,
        done: sendChatroomMsgDone
      })
      console.log('正在发送聊天室text消息, msg=', msg)
      function sendChatroomMsgDone (error, msg) {
        console.log('发送聊天室' + msg.type + '消息' + (!error ? '成功' : '失败') + ', id=' + msg, error, msg)
        if (!error) {
          let jsonCustom = JSON.parse(msg.custom)
          // console.log(jsonCustom)
          // console.log(msg.time)
          // console.log(v.liveStartTime)
          let sec = Math.floor((msg.time - v.liveStartTime) / 1000)
          let item = {
            time: v.$myutil.getDanmakuTimeStr(sec),
            sec: sec,
            user: jsonCustom.user.nickName,
            text: jsonCustom.text,
            avatar: jsonCustom.user.avatar,
            isSelf: true
          }
          v.listShow.push(item)
          v.$notify({
            title: '消息',
            message: '弹幕评论发送成功!',
            position: 'bottom-right',
            type: 'success',
            duration: 2000
          })
          let textSend = document.getElementById('textSend')
          textSend.focus()
          if (!v.paused) {
            v.$nextTick(function () {
              var divList = document.getElementById('danmakuList')
              divList.scrollTop = divList.scrollHeight
            })
          }
        }
      }
    },
    loadLrc (urlLrc) {
      var v = this
      v.clearListShow()
      v.notLive = true
      var divList = document.getElementById('danmakuList')
      // 下载弹幕载入listLrc
      v.$http({
        url: urlLrc
      }).then(function (res) {
        console.log(res)
        let reg = new RegExp(`\\[\\d{2}:\\d{2}:\\d{2}.\\d{1,3}\\]`, 'g')
        let listTime = res.data.match(reg)
        let listText = res.data.split(reg)
        let sumCount = 0
        for (var i = 0; i < listTime.length; i++) {
          let tempTime = listTime[i]
            .substr(2, listTime[i].length - 2)
            .split(':')
          let timeSec =
            parseInt(tempTime[0]) * 3600 +
            parseInt(tempTime[1]) * 60 +
            parseInt(tempTime[2])
          let temp = listText[i + 1].split(String.fromCharCode(9))
          let item = {
            time: listTime[i],
            sec: timeSec,
            user: temp[0],
            text: temp[1]
          }
          v.listLrc.push(item)
          sumCount++
          // 记录每个人发弹幕数量
          if (v.mapUserCount.has(item.user)) {
            v.mapUserCount.set(item.user, v.mapUserCount.get(item.user) + 1)
          } else {
            v.mapUserCount.set(item.user, 1)
          }
        }
        // 排个序 官方的弹幕记录顺序有可能是乱的..
        v.listLrc.sort(function (a, b) {
          return a.sec - b.sec
        })
        v.max = v.listLrc[v.listLrc.length - 1].sec

        // 播放弹幕 listShow
        v.paused = false
        v.err = '已载入重播弹幕评论' + ': 共' + v.mapUserCount.size + '人发送了' + sumCount + '条弹幕'
        v.InterShow = setInterval(function () {
          if (v.paused) {
            return
          }
          if ((v.listLrc.length <= 0) || (v.listLrc.length - 1 <= v.currentIndex)) {
            clearInterval(v.InterShow)
            console.log('清除定时器')
          } else {
            if (v.flagLocat) {
              v.currentTime = parseInt(v.position)
              v.flagLocat = false
              while (v.currentTime < v.listLrc[v.currentIndex].sec) {
                v.listShow.splice(v.currentIndex, 1)
                v.currentIndex--
              }
            }
            while (v.currentTime >= v.listLrc[v.currentIndex].sec) {
              v.listShow.push(v.listLrc[v.currentIndex])
              v.currentIndex++
            }
            v.$nextTick(function () {
              divList.scrollTop = divList.scrollHeight
            })
            v.currentTime++
            v.position = v.currentTime
          }
        }, 1000)
      }).catch(function (err) {
        v.err = '获取弹幕文件失败,或因弹幕文件还未生成'
        console.log(err)
      })
    }
  },
  mounted: function () {
    console.log(this.$route.query.isLive)
    // this.loadLrc('https://source.48.cn/mediasource/live/lrc/5b4df6a90cf2af641a23c584.lrc')
    this.sTitle = this.$route.query.title.replace('生成中', '')
    if (this.$route.query.isLive === 'true') {
      this.currentLiveRoomid = this.$route.query.roomId
      this.message += '(人数:' + this.$route.query.number + ')'
      this.getChatroom(this.$route.query.roomId, this.$route.query.liveId, this.$route.query.startTime)
    } else {
      this.message += '(人气值:' + this.$route.query.number + ')'
      this.loadLrc(this.$route.query.lrcPath)
    }
  }
}
</script>

<style scoped>
  #danmakuList {
    flex: 1;
    background-color: rgba(25, 25, 25, 0.9);
    color: white;
    font-family: 'Times New Roman', Times, serif;
    font-size: 13px;
    overflow-x: auto;
    overflow-y: auto;
    width: 100%;
    height: auto;
    min-height: 250px;
    max-height: 450px;
  }
  #danmakuBar {
    background-color: rgba(18, 18, 18, 0.9);
    color: aquamarine;
    width: 100%;
    height: 25px;
  }
  #sTitle {
    font-size: 12px;
  }
  #danmakuPanel {
    background-color: rgba(18, 18, 18, 0.9);
    color: white;
  }
  #user {
    color: skyblue;
  }
  #text {
    color: white;
  }
  #phone {
    color: rgb(98, 64, 250);
  }
  #time {
    color: rgb(248, 248, 225);
    background-color: blueviolet;
    opacity: 0.5;
  }
</style>